package sawyer;
/** TwitterInterface.java
 * @author shadowimmage@gmail.com Chase Sawyer
 *	Handles the main interaction with the Twitter servers through the twitter4j library.
 */

import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;

import twitter4j.*;
import twitter4j.conf.*;

public class TwitInterface {
	private Debug debug;
	private TwitterListener listener;
	private ConfigurationBuilder cb;
	private AsyncTwitter twitter;
	private static boolean initiated = false;
	
	public TwitInterface(Debug debug) {
		this.debug = debug;	//store debugger locally for use later.
		debug.print("initiating Twitter assets...");
		listener = constructListener();
		cb = new ConfigurationBuilder();
		cb.setDebugEnabled(true)
		  .setOAuthConsumerKey("SRogXU5lnDpMs6Wls6Eiw")
		  .setOAuthConsumerSecret("JIy0Ed0HKaeMTFoofEZcOh5y3RR9wAgxxsvJXZN3CQ")
		  .setOAuthAccessToken("23843783-0mIQSgEQ5NqDTLpkWDxYq3XJW105DFVBtZqEdYtQ")
		  .setOAuthAccessTokenSecret("Ib7tijplQwLF14OHYPaXB6iSTeOCViWbWtMUKl84jM");
		AsyncTwitterFactory tf = new AsyncTwitterFactory(cb.build());
		twitter = tf.getInstance();
		twitter.addListener(listener);
		initiated = true;
		debug.print("initiation complete.");
	}
	
	public static boolean initiated() {
		return initiated;
	}
	
	/** Call to shut down twitter4j resources and release them.
	 */
	public void shutdown() {
		twitter.shutdown();
	}
	
	/** Utility method to check that the program has successfully authenticated with the 
	 * Twitter servers.
	 * @return
	 */
	public String getScreenName() {
		try {
			debug.print("getting screen name...");
			return twitter.getScreenName();
		} catch (IllegalStateException | TwitterException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/** Sends out a new query. The results will be returned to the listener.
	 * @param term The current word to be looked for.
	 * @param count Number of results per 'page' TODO: what is a page?
	 */
	public void search(String term, int count) {
		debug.print("New query started: \"" + term + "\"");
		Query q = new Query(term);
		q.setCount(count);
		q.setResultType(Query.RECENT);
		twitter.search(q);
	}
	
	private TwitterListener constructListener() {
		TwitterListener listener = new TwitterAdapter() {
			
			/* Replaces callback from the ASYNC interface to capture returned results 
			 * from the previous search. 
			 * @see twitter4j.TwitterAdapter#searched(twitter4j.QueryResult)
			 */
			@Override
			public void searched(QueryResult result) {
				List<Status> results = result.getTweets();
				String firstTerm = Main.getCurrentTerm();
				String nextTerm = "";
				ListIterator<Status> itr = results.listIterator();
				while (itr.hasNext() && nextTerm.equals("")) { // check each result
					String stText = itr.next().getText();	//result text
					Scanner parser = new Scanner(stText);
					while (parser.hasNext()) {	// iterate over the words in the result
						if (parser.next().matches(firstTerm) && parser.hasNext()) { 
							// look for a word following the original search term.
							nextTerm = parser.next();
							if (nextTerm.matches("[@#]+")) {
								nextTerm = "";
							}
						}
					}
					parser.close();
				}
				Main.result(nextTerm);
				//TODO: At this point, I need to check the status of nextTerm, if it is
				// a word, then I can pass it over to the graphics engine, and if I didn't 
				// find anything, then I'll need to decide on how to continue.
				//TODO: Continuation can be in the selecting of a new word.
				//TODO: Selection of a new word should be out or a random pool of previously
				// 'seen' words. (TODO:new data struct in Main) 
				//TODO: Implement/copy over a fileI/O program to write logs(debug) and to 
				// write out completed paragraphs to disk.
				//TODO: FILEIO: Filenames will be time/date that paragraph is completed, txt files.
				//TODO: Some way for graphics to notify main loop to stop (program 
				// control/continuation needs to be centralized in Main so that graphics can 
				// halt iteration).
			} //end searched().
			
		};
		return listener;
	}

}
